import time

import pytest
from _pytest.config import ExitCode, Config
from _pytest.terminal import TerminalReporter

from handlers.handler_files.handler_yaml import HandlerYaml
from handlers.handler_request import HandlerSendRequest
from handlers.handler_log import logger
from testcase.validate_module.test_validate import TestValidate
from handlers.handler_basics import format_duration
from handlers.hanlder_dingding import send_msg


@pytest.fixture(scope="function")
def login_testcase(request):
    # 执行用例前需要优先执行的测试用例
    logger.info('............login用例的前置条件start.....................')
    data = HandlerYaml().reader_parametrize_specific_testcase_data(
        'validate_module',
        'captcha_image.yaml',
        1
    )
    TestValidate().test_validate_captcha_image(
        HandlerSendRequest(data)
    )
    logger.info('............login用例的前置条件end.....................')
    # 将参数化信息存储到发送请求接口中去
    return HandlerSendRequest(request.param)


@pytest.fixture(scope="function")
def send_request_object(request):
    return HandlerSendRequest(request.param)


@pytest.fixture(scope='function', autouse=True)
def setup_teardown(request):
    print('\n............start....................')
    yield
    print('\n.............end.....................\n')


def pytest_terminal_summary(terminalreporter: TerminalReporter, exitstatus: ExitCode, config: Config):
    """
    钩子函数 在终端摘要报告中添加一个部分。
    :param terminalreporter:
    :param exitstatus:
    :param config:
    :return:
    """
    # 测试用例总数
    testcase_total = terminalreporter._numcollected
    # 通过测试用例数量
    passed_number = len(terminalreporter.stats.get('passed', []))
    # 失败测试用例数量
    failed_number = len(terminalreporter.stats.get('failed', []))
    # 错误测试用例数量
    error_number = len(terminalreporter.stats.get('error', []))
    # 跳过测试用例数量
    skip_number = len(terminalreporter.stats.get('skipped', []))
    # 测试用例执行时间
    duration = round(time.time() - terminalreporter._sessionstarttime, 2)
    format_duration_ = format_duration(duration)
    # 统计 通过率 失败率 通过率
    pass_rate = f'{(passed_number / testcase_total) * 100:.0f}%' if testcase_total > 0 else 'N/A'
    fail_rate = f'{(failed_number / testcase_total) * 100:.0f}%' if testcase_total > 0 else 'N/A'
    error_rate = f'{(error_number / testcase_total) * 100:.0f}%' if testcase_total > 0 else 'N/A'
    summary = f"""
    自动化测试结果：
    测试用例总数：{testcase_total}
    通过测试用例数量: {passed_number}      通过率: {pass_rate}
    失败测试用例数量: {failed_number}      失败率: {fail_rate}
    错误测试用例数量: {error_number}       错误率: {error_rate}
    跳过测试用例数量: {skip_number}
    测试用例执行时间: 秒数：{duration}, 时间：{format_duration_}
    """
    send_msg(summary, at_all=True)
    print(summary)
